﻿using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Security.Permissions;

using BdcAdmin = Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.Office.Server.Utilities;
using Microsoft.BusinessData;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.MetadataModel;

namespace CenterSiteVSTemplateWizard
{
    static class Program
    {        
        public static EntityCenterInputForm form1 = null;
        public static EntityDetailsInputForm form2 = null;
        public static String URL;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            
            String fileName= null;
            String[] str = new String[7];
           

            if (args.Length >= 2)
            {
                fileName = args[0];
                URL = args[1];
            }
            else
            {
                fileName = Path.Combine(Path.GetTempPath(), "Temp.txt");
                URL = @"http://" + System.Environment.MachineName.ToLower() + @"/";
            }

            int templateID = getUniqueTemplateID();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            form1 = new EntityCenterInputForm();
            Application.Run(form1);
            int i = 0;

            str[i++] = templateID.ToString();
            str[i++] = form1.entityNameproperty;
            str[i++] = form1.entityNameSpaceproperty;
            str[i++] = form1.lobSystempInstanceroperty;
            str[i++] = form1.specificFinderproperty;
            str[i++] = form1.Finderproperty;       
            if(form2 != null)
                str[i++] = form2.entityfieldsroperty;

            File.WriteAllLines(fileName, str);           
           
        }

        /* the Following Function returns the Unique tempalte ID. the ID will be greater then 10050 */
        /* 14483 is sharepoint standard tempalteID */

        static int getUniqueTemplateID()
        {
            SPSite site = new SPSite(URL);
            SPWebTemplateCollection wtcoll = site.GetWebTemplates(1033);
            int ID = 10050;           

            foreach (SPWebTemplate wt in wtcoll)
            {
                if (ID < wt.ID && wt.ID != 14483)
                    ID = wt.ID;
            }
            return ID+1;
        }
    }
}
